package com.xuanzheng.company.dao.impl;

import com.xuanzheng.company.dao.AttendanceSettingDao;
import com.xuanzheng.company.entity.AttendanceSetting;
import com.xuanzheng.company.util.DBUtil;
import com.xuanzheng.company.util.IdGenerator;

import java.sql.*;

public class AttendanceSettingDaoImpl implements AttendanceSettingDao {

    @Override
    public AttendanceSetting getByCompanyId(String companyId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        AttendanceSetting setting = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT a.*, c.name as company_name FROM attendance_setting a " +
                    "LEFT JOIN company c ON a.company_id = c.id " +
                    "WHERE a.company_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                setting = mapResultSetToAttendanceSetting(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return setting;
    }

    @Override
    public int saveOrUpdate(AttendanceSetting setting) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;

        try {
            conn = DBUtil.getConnection();
            
            // 检查是否已存在该公司的打卡设置
            AttendanceSetting existingSetting = getByCompanyId(setting.getCompanyId());
            
            if (existingSetting == null) {
                // 不存在，执行插入操作
                String sql = "INSERT INTO attendance_setting (id, company_id, check_in_start_time, check_in_end_time, " +
                        "check_out_start_time, check_out_end_time, max_attendance_hours, attendance_percentage, task_percentage) " +
                        "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                pstmt = conn.prepareStatement(sql);
                
                // 生成唯一ID
                String id = IdGenerator.generateId();
                setting.setId(id);
                
                pstmt.setString(1, setting.getId());
                pstmt.setString(2, setting.getCompanyId());
                pstmt.setTime(3, setting.getCheckInStartTime());
                pstmt.setTime(4, setting.getCheckInEndTime());
                pstmt.setTime(5, setting.getCheckOutStartTime());
                pstmt.setTime(6, setting.getCheckOutEndTime());
                pstmt.setDouble(7, setting.getMaxAttendanceHours() != null ? setting.getMaxAttendanceHours() : 8.0);
                pstmt.setDouble(8, setting.getAttendancePercentage() != null ? setting.getAttendancePercentage() : 0.5);
                pstmt.setDouble(9, setting.getTaskPercentage() != null ? setting.getTaskPercentage() : 0.5);
            } else {
                // 已存在，执行更新操作
                String sql = "UPDATE attendance_setting SET check_in_start_time = ?, check_in_end_time = ?, " +
                        "check_out_start_time = ?, check_out_end_time = ?, max_attendance_hours = ?, " +
                        "attendance_percentage = ?, task_percentage = ? WHERE id = ?";
                pstmt = conn.prepareStatement(sql);
                
                pstmt.setTime(1, setting.getCheckInStartTime());
                pstmt.setTime(2, setting.getCheckInEndTime());
                pstmt.setTime(3, setting.getCheckOutStartTime());
                pstmt.setTime(4, setting.getCheckOutEndTime());
                pstmt.setDouble(5, setting.getMaxAttendanceHours() != null ? setting.getMaxAttendanceHours() : 8.0);
                pstmt.setDouble(6, setting.getAttendancePercentage() != null ? setting.getAttendancePercentage() : 0.5);
                pstmt.setDouble(7, setting.getTaskPercentage() != null ? setting.getTaskPercentage() : 0.5);
                pstmt.setString(8, existingSetting.getId());
                
                // 设置ID，用于返回
                setting.setId(existingSetting.getId());
            }
            
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        return result;
    }

    @Override
    public int delete(String id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM attendance_setting WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }

    private AttendanceSetting mapResultSetToAttendanceSetting(ResultSet rs) throws SQLException {
        AttendanceSetting setting = new AttendanceSetting();
        setting.setId(rs.getString("id"));
        setting.setCompanyId(rs.getString("company_id"));
        setting.setCheckInStartTime(rs.getTime("check_in_start_time"));
        setting.setCheckInEndTime(rs.getTime("check_in_end_time"));
        setting.setCheckOutStartTime(rs.getTime("check_out_start_time"));
        setting.setCheckOutEndTime(rs.getTime("check_out_end_time"));
        setting.setMaxAttendanceHours(rs.getDouble("max_attendance_hours"));
        setting.setAttendancePercentage(rs.getDouble("attendance_percentage"));
        setting.setTaskPercentage(rs.getDouble("task_percentage"));
        setting.setCreateTime(rs.getTimestamp("create_time"));
        setting.setUpdateTime(rs.getTimestamp("update_time"));
        
        // 额外字段
        if (rs.getString("company_name") != null) {
            setting.setCompanyName(rs.getString("company_name"));
        }
        
        return setting;
    }
} 